package twentytwentyone_3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2021-03-22 14:17
 * @Modified By:
 */
public class FindRestaurant_599 {
    public static void main(String[] args){
        String[] list1 = new String[]{"Shogun", "KFC"};
        String[] list2 = new String[]{"KFC", "Shogun"};
        System.out.println(Arrays.toString(findRestaurant(list1, list2)));
    }

    public static String[] findRestaurant(String[] list1,String[] list2){
        // 将每个String的长度和其值存在MAP中
        HashMap< Integer, List < String >> map = new HashMap < > ();
        for (int i = 0; i < list1.length; i++) {
            for (int j = 0; j < list2.length; j++) {
                if (list1[i].equals(list2[j])) {
                    if (!map.containsKey(i + j))
                        map.put(i + j, new ArrayList < String > ());
                    map.get(i + j).add(list1[i]);
                }
            }
        }
        int min_index_sum = Integer.MAX_VALUE;
        // 遍历取出值小的key值也就是最小的索引长度
        for (int key: map.keySet())
            min_index_sum = Math.min(min_index_sum, key);
        String[] res = new String[map.get(min_index_sum).size()];
        return map.get(min_index_sum).toArray(res);
    }
}
